export default class Snake {
    constructor() {
        this.element = document.getElementById("snake");
        this.header = document.querySelector('.snake_header');
        this.bodies = this.element.getElementsByTagName("div");
    }
    get X() {
        return this.header.offsetLeft;
    }
    get Y() {
        return this.header.offsetTop;
    }
    set X(value) {
        if (value === this.X)
            return;
        if (this.bodies[1] && this.bodies[1].offsetLeft === value) {
            if (this.X > value) {
                value += 20;
            }
            else {
                value -= 20;
            }
        }
        if (value < 0 || value > 290)
            throw new Error("撞墙了");
        this.moveBody();
        this.header.style.left = value + "px";
        this.checkEatSelf();
    }
    set Y(value) {
        if (value === this.Y)
            return;
        if (this.bodies[1] && this.bodies[1].offsetTop === value) {
            if (this.Y > value) {
                value += 20;
            }
            else {
                value -= 20;
            }
        }
        if (value < 0 || value > 290)
            throw new Error("撞墙了");
        this.moveBody();
        this.header.style.top = value + "px";
        this.checkEatSelf();
    }
    addBody() {
        const div = document.createElement("div");
        div.className = "sanke_body";
        this.element.append(div);
    }
    moveBody() {
        for (let i = this.bodies.length - 1; i > 0; i--) {
            const Y = this.bodies[i - 1].offsetTop;
            const X = this.bodies[i - 1].offsetLeft;
            this.bodies[i].style.left = X + "px";
            this.bodies[i].style.top = Y + "px";
        }
    }
    checkEatSelf() {
        for (let i = 1; i < this.bodies.length; i++) {
            if (this.bodies[i].offsetLeft === this.X && this.bodies[i].offsetTop === this.Y) {
                throw new Error("撞到了自己");
            }
        }
    }
}
